package com.hns.its.persistence.jpa;

import com.hns.its.common.utils.AppUtils;
import com.hns.its.common.utils.Collections3;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SearchFilter {

	public enum Operator {
		EQ, LIKE, GT, LT, GTE, LTE, IN, NE, SPACE, NN, ISN
	}

	public String fieldName;
	public Object value;
	public Operator operator;

	public SearchFilter(String fieldName, Operator operator, Object value) {
		this.fieldName = fieldName;
		this.value = value;
		this.operator = operator;
	}

	/**
	 * searchParams中key的格式为OPERATOR_FIELDNAME
	 */
	public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = new LinkedHashMap<String, SearchFilter>();//Maps.newHashMap();

		for (Entry<String, Object> entry : searchParams.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (AppUtils.isNotEmpty(value)) {
				String[] names = StringUtils.split(key, "_",2);
				if (names.length < 2) {
					continue;
				}
				
				String filedName = null;
				if (names.length == 2) {
					filedName = StringUtils.replaceFirst(names[1], "_", ".");
				} else {
					List<String> list = Arrays.asList(names).subList(1, names.length);
					filedName = Collections3.convertToString(list, ".");
				}

				Operator operator = Operator.valueOf(names[0].toUpperCase());
				SearchFilter filter = new SearchFilter(filedName, operator, value);
				filters.put(key, filter);
			}
		}

		return filters;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "SearchFilter [fieldName=" + fieldName + ", value=" + value + ", operator=" + operator + "]";
	}

}
